import easygui as eg
from database import Database
from datetime import datetime


def get_group_status(status):
    """获取旅游团状态文本"""
    status_map = {
        'pending': '待确认',
        'confirmed': '已确认',
        'completed': '已完成',
        'cancelled': '已取消'
    }
    return status_map.get(status, status)


def add_travel_group(db):
    """添加新旅游团"""
    # 获取可用线路
    routes = db.execute_query("""
        SELECT RouteID, RouteName, Destination, Days, Price 
        FROM TravelRoutes 
        WHERE Status = 1
        ORDER BY RouteName
    """)

    if not routes:
        eg.msgbox("没有可用的旅游线路，请先添加线路", "错误")
        return

    # 格式化线路选择
    route_choices = [
        f"ID:{r['RouteID']} | {r['RouteName']} | {r['Destination']} | {r['Days']}天 | {r['Price']}元"
        for r in routes
    ]

    # 第一步：选择线路
    route_choice = eg.choicebox("选择旅游线路", "添加旅游团", route_choices)
    if not route_choice:
        return

    route_id = int(route_choice.split("ID:")[1].split("|")[0].strip())

    # 第二步：输入旅游团信息
    fields = [
        "团名称*",
        "出发日期(YYYY-MM-DD)*",
        "结束日期(YYYY-MM-DD)*",
        "最大人数*",
        "状态(pending/confirmed/completed/cancelled)*"
    ]
    values = eg.multenterbox("填写旅游团信息", "添加旅游团", fields)

    if not values:
        return

    group_name, start_date, end_date, max_people, status = values

    # 验证输入
    if not all([group_name, start_date, end_date, max_people, status]):
        eg.msgbox("带*的字段为必填项", "错误")
        return

    if status not in ['pending', 'confirmed', 'completed', 'cancelled']:
        eg.msgbox("状态必须是pending/confirmed/completed/cancelled", "错误")
        return

    try:
        # 转换日期格式
        start_date = datetime.strptime(start_date, "%Y-%m-%d")
        end_date = datetime.strptime(end_date, "%Y-%m-%d")
        max_people = int(max_people)

        if start_date >= end_date:
            eg.msgbox("结束日期必须晚于出发日期", "错误")
            return

        # 插入数据库
        db.execute_query("""
            INSERT INTO TravelGroups (
                RouteID, GroupName, StartDate, EndDate, 
                MaxPeople, CurrentPeople, Status
            ) VALUES (?, ?, ?, ?, ?, 0, ?)
        """, (route_id, group_name, start_date, end_date, max_people, status), False)

        eg.msgbox("旅游团添加成功", "成功")
    except ValueError:
        eg.msgbox("日期格式应为YYYY-MM-DD，人数必须为数字", "错误")
    except Exception as e:
        eg.msgbox(f"添加失败: {str(e)}", "错误")


def edit_group_info(db, group_id):
    """编辑旅游团信息"""
    # 获取当前信息
    group = db.execute_query("""
        SELECT tg.*, tr.RouteName
        FROM TravelGroups tg
        JOIN TravelRoutes tr ON tg.RouteID = tr.RouteID
        WHERE tg.GroupID = ?
    """, (group_id,))[0]

    # 获取可用线路
    routes = db.execute_query("""
        SELECT RouteID, RouteName FROM TravelRoutes WHERE Status = 1
    """)

    # 创建线路选择列表
    route_choices = [f"ID:{r['RouteID']} | {r['RouteName']}" for r in routes]
    current_route = f"ID:{group['RouteID']} | {group['RouteName']}"

    fields = [
        "团名称*",
        "线路*",
        "出发日期(YYYY-MM-DD)*",
        "结束日期(YYYY-MM-DD)*",
        "最大人数*",
        "当前人数",
        "状态(pending/confirmed/completed/cancelled)*"
    ]
    values = [
        group['GroupName'],
        current_route,
        group['StartDate'].strftime("%Y-%m-%d"),
        group['EndDate'].strftime("%Y-%m-%d"),
        str(group['MaxPeople']),
        str(group['CurrentPeople']),
        group['Status']
    ]

    new_values = eg.multenterbox("编辑旅游团信息", "旅游团编辑", fields, values)

    if not new_values:
        return

    # 验证必填字段
    if not all(new_values[:5] + [new_values[6]]):
        eg.msgbox("带*的字段为必填项", "错误")
        return

    if new_values[6] not in ['pending', 'confirmed', 'completed', 'cancelled']:
        eg.msgbox("状态必须是pending/confirmed/completed/cancelled", "错误")
        return

    try:
        # 解析新线路ID
        new_route_id = int(new_values[1].split("ID:")[1].split("|")[0].strip())
        start_date = datetime.strptime(new_values[2], "%Y-%m-%d")
        end_date = datetime.strptime(new_values[3], "%Y-%m-%d")
        max_people = int(new_values[4])
        current_people = int(new_values[5])

        if start_date >= end_date:
            eg.msgbox("结束日期必须晚于出发日期", "错误")
            return

        if current_people > max_people:
            eg.msgbox("当前人数不能超过最大人数", "错误")
            return

        # 更新数据库
        db.execute_query("""
            UPDATE TravelGroups SET
                RouteID = ?, GroupName = ?, StartDate = ?, EndDate = ?,
                MaxPeople = ?, CurrentPeople = ?, Status = ?
            WHERE GroupID = ?
        """, (
            new_route_id, new_values[0], start_date, end_date,
            max_people, current_people, new_values[6], group_id
        ), False)

        eg.msgbox("旅游团信息更新成功", "成功")
    except ValueError:
        eg.msgbox("日期格式应为YYYY-MM-DD，人数必须为数字", "错误")
    except Exception as e:
        eg.msgbox(f"更新失败: {str(e)}", "错误")


def assign_guide(db, group_id):
    """为旅游团分配导游"""
    # 获取当前分配的导游
    current_guide = db.execute_query("""
        SELECT g.GuideID, u.RealName 
        FROM Guides g
        JOIN Users u ON g.UserID = u.UserID
        WHERE g.GuideID = (
            SELECT GuideID FROM TravelGroups WHERE GroupID = ?
        )
    """, (group_id,))

    # 获取所有可用导游
    guides = db.execute_query("""
        SELECT g.GuideID, u.RealName, g.LicenseNumber
        FROM Guides g
        JOIN Users u ON g.UserID = u.UserID
        WHERE u.Status = 1
        ORDER BY u.RealName
    """)

    if not guides:
        eg.msgbox("没有可用的导游", "错误")
        return

    # 格式化导游选择
    guide_choices = [f"ID:{g['GuideID']} | {g['RealName']} | 导游证:{g['LicenseNumber']}" for g in guides]

    # 如果有当前导游，设置为默认选择
    default = None
    if current_guide:
        default = f"ID:{current_guide[0]['GuideID']} | {current_guide[0]['RealName']}"

    # 选择导游
    choice = eg.choicebox("选择导游", "分配导游", guide_choices, default)
    if not choice:
        return

    guide_id = int(choice.split("ID:")[1].split("|")[0].strip())

    try:
        # 更新数据库
        db.execute_query("""
            UPDATE TravelGroups SET GuideID = ? WHERE GroupID = ?
        """, (guide_id, group_id), False)

        eg.msgbox("导游分配成功", "成功")
    except Exception as e:
        eg.msgbox(f"分配失败: {str(e)}", "错误")


def view_group_details(db, group_id):
    """查看旅游团详细信息"""
    # 获取旅游团基本信息
    group = db.execute_query("""
        SELECT tg.*, tr.RouteName, tr.Destination, tr.Days, tr.Price,
               u.RealName AS GuideName, u.Phone AS GuidePhone
        FROM TravelGroups tg
        JOIN TravelRoutes tr ON tg.RouteID = tr.RouteID
        LEFT JOIN Guides g ON tg.GuideID = g.GuideID
        LEFT JOIN Users u ON g.UserID = u.UserID
        WHERE tg.GroupID = ?
    """, (group_id,))[0]

    # 获取团员列表
    members = db.execute_query("""
        SELECT t.TouristID, u.RealName, t.IDNumber, u.Phone,
               gm.JoinTime, gm.Status, gm.PaymentStatus
        FROM GroupMembers gm
        JOIN Tourists t ON gm.TouristID = t.TouristID
        JOIN Users u ON t.UserID = u.UserID
        WHERE gm.GroupID = ?
        ORDER BY gm.JoinTime
    """, (group_id,))

    # 构建显示信息
    info = f"=== 基本信息 ===\n"
    info += f"团ID: {group['GroupID']}\n"
    info += f"团名称: {group['GroupName']}\n"
    info += f"线路: {group['RouteName']}\n"
    info += f"目的地: {group['Destination']}\n"
    info += f"天数: {group['Days']}天\n"
    info += f"价格: {group['Price']}元\n"
    info += f"出发日期: {group['StartDate'].strftime('%Y-%m-%d')}\n"
    info += f"结束日期: {group['EndDate'].strftime('%Y-%m-%d')}\n"
    info += f"最大人数: {group['MaxPeople']}\n"
    info += f"当前人数: {group['CurrentPeople']}\n"
    info += f"状态: {get_group_status(group['Status'])}\n"

    if group['GuideName']:
        info += f"\n=== 导游信息 ===\n"
        info += f"姓名: {group['GuideName']}\n"
        info += f"联系电话: {group['GuidePhone'] or '无'}\n"
    else:
        info += f"\n=== 未分配导游 ===\n"

    if members:
        info += f"\n=== 团员列表 ===\n"
        for m in members:
            info += (
                f"ID:{m['TouristID']} | 姓名:{m['RealName']} | "
                f"身份证:{m['IDNumber']}\n"
                f"电话:{m['Phone'] or '无'} | "
                f"加入时间:{m['JoinTime'].strftime('%Y-%m-%d %H:%M')}\n"
                f"状态:{get_member_status(m['Status'])} | "
                f"支付:{'已支付' if m['PaymentStatus'] else '未支付'}\n\n"
            )
    else:
        info += f"\n=== 暂无团员 ===\n"

    eg.textbox("旅游团详细信息", "旅游团详情", info)


def get_member_status(status):
    """获取团员状态文本"""
    status_map = {
        'pending': '待确认',
        'confirmed': '已确认',
        'cancelled': '已取消'
    }
    return status_map.get(status, status)


def show_group_management(db, current_user):
    """显示旅游团管理主界面"""
    while True:
        # 获取旅游团列表
        groups = db.execute_query("""
            SELECT tg.GroupID, tg.GroupName, tr.RouteName, 
                   tg.StartDate, tg.EndDate, tg.MaxPeople, tg.CurrentPeople,
                   u.RealName AS GuideName, tg.Status
            FROM TravelGroups tg
            JOIN TravelRoutes tr ON tg.RouteID = tr.RouteID
            LEFT JOIN Guides g ON tg.GuideID = g.GuideID
            LEFT JOIN Users u ON g.UserID = u.UserID
            ORDER BY tg.StartDate DESC
        """)

        if not groups:
            eg.msgbox("没有旅游团数据", "旅游团管理")
            break

        # 格式化显示
        group_list = [
            f"ID:{g['GroupID']} | 团名:{g['GroupName']} | 线路:{g['RouteName']} | "
            f"时间:{g['StartDate'].strftime('%Y-%m-%d')}到{g['EndDate'].strftime('%Y-%m-%d')} | "
            f"人数:{g['CurrentPeople']}/{g['MaxPeople']} | "
            f"导游:{g['GuideName'] or '未分配'} | 状态:{get_group_status(g['Status'])}"
            for g in groups
        ]

        # 添加操作选项
        group_list.extend(
            ["", "=== 操作选项 ===", "1. 添加旅游团", "2. 查看详情", "3. 编辑信息", "4. 分配导游", "5. 返回"])

        choice = eg.choicebox("旅游团管理系统", "旅游团管理", group_list)

        if not choice or choice == "5. 返回":
            break

        if choice == "1. 添加旅游团":
            add_travel_group(db)
        elif choice == "2. 查看详情":
            group_id = get_id_from_choice(choice)
            if group_id:
                view_group_details(db, group_id)
        elif choice == "3. 编辑信息":
            group_id = get_id_from_choice(choice)
            if group_id:
                edit_group_info(db, group_id)
        elif choice == "4. 分配导游":
            group_id = get_id_from_choice(choice)
            if group_id:
                assign_guide(db, group_id)


def get_id_from_choice(choice):
    """从选择项中提取ID"""
    if "ID:" not in choice:
        return None
    return int(choice.split("ID:")[1].split("|")[0].strip())